package com.example.smartcity.net;

import android.app.Activity;
import android.content.SharedPreferences;
import android.widget.Toast;

import com.example.smartcity.LoginActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 封装 http 请求
 *
 * @author YSJ
 * @date 2021/4/19 : 19:43
 */

//好处 减少代码量，减少BUG ，更容易扩展，。。。。
// 抽取公共部分

public class OkhttpHelper {


    public <T> void post(HashMap<String, String> map, String url, Activity activity, MyHttpCallBack<T> myHttpCallBack, Class<T> classOfT) throws Exception {
        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        JSONObject jsonObject = new JSONObject();

        for (Map.Entry<String, String> entry : map.entrySet()) {
            jsonObject.put(entry.getKey(), entry.getValue());
        }
        RequestBody body = RequestBody.create(jsonObject.toString(), mediaType);

        Request request = new Request.Builder()
                .post(body)
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                Gson gson = new Gson();
                //固定的寫法

                Object t = gson.fromJson(string, classOfT);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        myHttpCallBack.onResponse((T) t, string);
                    }
                });

            }
        });

    }


    public <T> void get(HashMap<String, String> map, String url, Activity activity, MyHttpCallBack<T> myHttpCallBack, Class<T> classOfT) throws Exception {
        OkHttpClient client = new OkHttpClient();

        url += "?";
        if (map != null)
            for (Map.Entry<String, String> entry : map.entrySet()) {
                url += entry.getKey() + "=" + entry.getValue();
                url += "&";
            }
        url.substring(0, url.length() - 1);

        SharedPreferences sp = activity.getSharedPreferences("app",0);
        String token = sp.getString("token", "");
        Request request = new Request.Builder()
                .get()
                .addHeader("Authorization", token)
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                Gson gson = new Gson();
                //固定的寫法

                Object t = gson.fromJson(string, classOfT);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        myHttpCallBack.onResponse((T) t, string);
                    }
                });

            }
        });

    }
}
